package com.yuntoyun.fwcore.util;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.RequiresPermission;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

import static android.Manifest.permission.CALL_PHONE;
import static android.Manifest.permission.READ_PHONE_STATE;

//手机工具类
public class FwPhoneUtil {

    private static FwPhoneUtil init = null;

    public static synchronized FwPhoneUtil builder() {
        if (null == init) {
            init = new FwPhoneUtil();
        }
        return init;
    }

    private FwPhoneUtil() {
        if (null != init) {
            throw new UnsupportedOperationException("不支持调用！");
        }
    }

    /**
     * Return whether the device is phone.
     *
     * @return {@code true}: yes<br>{@code false}: no
     */
    public boolean isPhone() {
        TelephonyManager tm =
                (TelephonyManager) FwApplicationUtil.appContext().getSystemService(Context
                        .TELEPHONY_SERVICE);
        return tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
    }

    /**
     * Return the unique device id.
     * <p>Must hold
     * {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
     *
     * @return the unique device id
     */
    @SuppressLint("HardwareIds")
    @RequiresPermission(READ_PHONE_STATE)
    public String getDeviceId() {
        TelephonyManager tm =
                (TelephonyManager) FwApplicationUtil.appContext().getSystemService(Context
                        .TELEPHONY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (tm == null) return "";
            String imei = tm.getImei();
            if (!TextUtils.isEmpty(imei)) return imei;
            String meid = tm.getMeid();
            return TextUtils.isEmpty(meid) ? "" : meid;

        }
        return tm != null ? tm.getDeviceId() : "";
    }

    /**
     * Return the serial of device.
     *
     * @return the serial of device
     */
    @SuppressLint("HardwareIds")
    @RequiresPermission(READ_PHONE_STATE)
    public String getSerial() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? Build.getSerial() : Build.SERIAL;
    }

    /**
     * Return the IMEI.
     * <p>Must hold
     * {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
     *
     * @return the IMEI
     */
    @SuppressLint("HardwareIds")
    @RequiresPermission(READ_PHONE_STATE)
    public String getIMEI() {
        TelephonyManager tm =
                (TelephonyManager) FwApplicationUtil.appContext().getSystemService(Context
                        .TELEPHONY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return tm != null ? tm.getImei() : "";
        }
        return tm != null ? tm.getDeviceId() : "";
    }

    /**
     * Return the MEID.
     * <p>Must hold
     * {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
     *
     * @return the MEID
     */
    @SuppressLint("HardwareIds")
    @RequiresPermission(READ_PHONE_STATE)
    public String getMEID() {
        TelephonyManager tm =
                (TelephonyManager) FwApplicationUtil.appContext().getSystemService(Context
                        .TELEPHONY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return tm != null ? tm.getMeid() : "";
        } else {
            return tm != null ? tm.getDeviceId() : "";
        }
    }

    /**
     * Return the IMSI.
     * <p>Must hold
     * {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
     *
     * @return the IMSI
     */
    @SuppressLint("HardwareIds")
    @RequiresPermission(READ_PHONE_STATE)
    public String getIMSI() {
        TelephonyManager tm =
                (TelephonyManager) FwApplicationUtil.appContext().getSystemService(Context
                        .TELEPHONY_SERVICE);
        return tm != null ? tm.getSubscriberId() : "";
    }

    /**
     * Returns the current phone type.
     *
     * @return the current phone type
     * <ul>
     * <li>{@link TelephonyManager#PHONE_TYPE_NONE}</li>
     * <li>{@link TelephonyManager#PHONE_TYPE_GSM }</li>
     * <li>{@link TelephonyManager#PHONE_TYPE_CDMA}</li>
     * <li>{@link TelephonyManager#PHONE_TYPE_SIP }</li>
     * </ul>
     */
    public int getPhoneType() {
        TelephonyManager tm =
                (TelephonyManager) FwApplicationUtil.appContext().getSystemService(Context
                        .TELEPHONY_SERVICE);
        return tm != null ? tm.getPhoneType() : -1;
    }

    /**
     * Return whether sim card state is ready.
     *
     * @return {@code true}: yes<br>{@code false}: no
     */
    public boolean isSimCardReady() {
        TelephonyManager tm =
                (TelephonyManager) FwApplicationUtil.appContext().getSystemService(Context
                        .TELEPHONY_SERVICE);
        return tm != null && tm.getSimState() == TelephonyManager.SIM_STATE_READY;
    }

    /**
     * Return the sim operator name.
     *
     * @return the sim operator name
     */
    public String getSimOperatorName() {
        TelephonyManager tm =
                (TelephonyManager) FwApplicationUtil.appContext().getSystemService(Context
                        .TELEPHONY_SERVICE);
        return tm != null ? tm.getSimOperatorName() : "";
    }

    /**
     * Return the sim operator using mnc.
     *
     * @return the sim operator
     */
    public String getSimOperatorByMnc() {
        TelephonyManager tm =
                (TelephonyManager) FwApplicationUtil.appContext().getSystemService(Context
                        .TELEPHONY_SERVICE);
        String operator = tm != null ? tm.getSimOperator() : null;
        if (operator == null) return null;
        switch (operator) {
            case "46000":
            case "46002":
            case "46007":
            case "46020":
                return "中国移动";
            case "46001":
            case "46006":
            case "46009":
                return "中国联通";
            case "46003":
            case "46005":
            case "46011":
                return "中国电信";
            default:
                return operator;
        }
    }

    /**
     * Return the phone status.
     * <p>Must hold
     * {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
     *
     * @return DeviceId = 99000311726612<br>
     * DeviceSoftwareVersion = 00<br>
     * Line1Number =<br>
     * NetworkCountryIso = cn<br>
     * NetworkOperator = 46003<br>
     * NetworkOperatorName = 中国电信<br>
     * NetworkType = 6<br>
     * PhoneType = 2<br>
     * SimCountryIso = cn<br>
     * SimOperator = 46003<br>
     * SimOperatorName = 中国电信<br>
     * SimSerialNumber = 89860315045710604022<br>
     * SimState = 5<br>
     * SubscriberId(IMSI) = 460030419724900<br>
     * VoiceMailNumber = *86<br>
     */
    @SuppressLint("HardwareIds")
    @RequiresPermission(READ_PHONE_STATE)
    public String getPhoneStatus() {
        TelephonyManager tm =
                (TelephonyManager) FwApplicationUtil.appContext().getSystemService(Context
                        .TELEPHONY_SERVICE);
        if (tm == null) return "";
        String str = "";
        str += "DeviceId(IMEI) = " + tm.getDeviceId() + "\n";
        str += "DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion() + "\n";
        str += "Line1Number = " + tm.getLine1Number() + "\n";
        str += "NetworkCountryIso = " + tm.getNetworkCountryIso() + "\n";
        str += "NetworkOperator = " + tm.getNetworkOperator() + "\n";
        str += "NetworkOperatorName = " + tm.getNetworkOperatorName() + "\n";
        str += "NetworkType = " + tm.getNetworkType() + "\n";
        str += "PhoneType = " + tm.getPhoneType() + "\n";
        str += "SimCountryIso = " + tm.getSimCountryIso() + "\n";
        str += "SimOperator = " + tm.getSimOperator() + "\n";
        str += "SimOperatorName = " + tm.getSimOperatorName() + "\n";
        str += "SimSerialNumber = " + tm.getSimSerialNumber() + "\n";
        str += "SimState = " + tm.getSimState() + "\n";
        str += "SubscriberId(IMSI) = " + tm.getSubscriberId() + "\n";
        str += "VoiceMailNumber = " + tm.getVoiceMailNumber() + "\n";
        return str;
    }

    /**
     * Skip to dial.
     *
     * @param phoneNumber The phone number.
     */
    public void dial(final String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
        FwApplicationUtil.appContext().startActivity(intent.addFlags(Intent
                .FLAG_ACTIVITY_NEW_TASK));
    }

    /**
     * Make a phone call.
     * <p>Must hold {@code <uses-permission android:name="android.permission.CALL_PHONE" />}</p>
     *
     * @param phoneNumber The phone number.
     */
    @RequiresPermission(CALL_PHONE)
    public void call(final String phoneNumber) {
        Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phoneNumber));
        FwApplicationUtil.appContext().startActivity(intent.addFlags(Intent
                .FLAG_ACTIVITY_NEW_TASK));
    }

    /**
     * Send sms.
     *
     * @param phoneNumber The phone number.
     * @param content     The content.
     */
    public void sendSms(final String phoneNumber, final String content) {
        Uri uri = Uri.parse("smsto:" + phoneNumber);
        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
        intent.putExtra("sms_body", content);
        FwApplicationUtil.appContext().startActivity(intent.addFlags(Intent
                .FLAG_ACTIVITY_NEW_TASK));
    }

    /**
     * 拔打电话( 多个号码保存在json数组中)
     *
     * @param jarr     号码字符串json数组
     * @param activity
     */
    public void dialMultiPhone(JsonArray jarr, final Activity activity) {
        if (null == jarr) return;

        StringBuffer sb = new StringBuffer("");
        for (JsonElement je : jarr) {
            sb.append(",");
            sb.append(je.getAsString());
        }
        if (sb.length() > 0) {
            dialMultiPhone(sb.substring(1), activity);
        }
    }

    /**
     * 拔打电话( 多个号码以英文逗号间隔)
     *
     * @param telNum   多个号码以英文逗号间隔
     * @param activity
     */
    public void dialMultiPhone(String telNum, final Activity activity) {

        try {
            if (!TextUtils.isEmpty(telNum)) {
                String[] splitTel = telNum.split(",");
                List<String> list = new ArrayList<String>();
                for (int i = 0; i < splitTel.length; i++) {
                    String tels = splitTel[i].trim();
                    if (!TextUtils.isEmpty(tels)) {
                        list.add(tels);
                    }
                }
                final String[] telArray = (String[]) list
                        .toArray(new String[list.size()]);
                if (telArray != null) {
                    if (telArray.length == 1) {
                        callPhone(telArray[0], activity);
                    } else {
                        new AlertDialog.Builder(activity).setTitle("拨打电话")
                                .setItems(telArray, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface arg0,
                                                        int arg1) {
                                        callPhone(telArray[arg1], activity);
                                    }
                                }).show();
                    }
                }

            } else {
                FwToastUtil.builder().makeText("暂时没有联系电话!");
            }
        } catch (Exception e) {
            FwLogUtil.error(e.getMessage());
        }
    }

    /**
     * 内置打电话方法
     *
     * @param tel
     * @param activity
     */
    private void callPhone(String tel, Activity activity) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
        activity.startActivity(intent);
    }
}
